from sre_parse import Verbose

from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
from django.urls import reverse
from slugify import slugify


class ArticleColumn(models.Model):
    """文章栏目"""
    user = models.ForeignKey(
        User, related_name="article_column", verbose_name="作者",
        on_delete=models.CASCADE)
    column = models.CharField(max_length=200, verbose_name="栏目名称")
    created = models.DateField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        verbose_name = "文章栏目"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.column


class ArticlePost(models.Model):
    author = models.ForeignKey(
        User, related_name="article", verbose_name="作者",
        on_delete=models.CASCADE
    )
    title = models.CharField(max_length=200, verbose_name="标题")
    slug = models.SlugField(max_length=500, verbose_name="永久链接")
    column = models.ForeignKey(
        ArticleColumn, related_name="article_column", verbose_name="栏目名称",
        on_delete=models.CASCADE
    )
    body = models.TextField(verbose_name="内容")
    created = models.DateTimeField(default=timezone.now())
    updated = models.DateTimeField(auto_now=True)
    users_like = models.ManyToManyField(User, related_name="article_like", blank=True)

    class Meta:
        verbose_name = "文章"
        verbose_name_plural = verbose_name
        ordering = ("-updated",)  # 排序方式为按编辑时间倒序
        index_together = (('id', 'slug'),)  # 索引字段
    
    def __str__(self):
        return self.title
    
    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(ArticlePost, self).save(*args, **kwargs)
    
    def get_absolute_url(self):  # 获取文章URL
        return reverse("article:article_detail", args=[self.id, self.slug])

    def get_url(self):
        return reverse("article:list_article_detail", args=[self.id, self.slug])
